
import HyphenateChat

//TODO: - 群聊
extension PixelWorldChatWrapper {
    
    //TODO: - 创建群组
    func createGroup() -> String {
        let options = EMGroupOptions()
        options.isInviteNeedConfirm = false
        options.maxUsers = 2000
        options.style = EMGroupStylePublicOpenJoin
        
        var error: EMError?
        let group = PixelWorldChatEMClient.groupManager.createGroup(withSubject: randomString(), description: randomString(), invitees: [], message: "", setting: options, error: &error)
        if error == nil {
            return group?.groupId ?? ""
        } else {
            return ""
        }
    }
    
    //TODO: - 加入群组
    func joinGroup(_ groupId: String) -> Bool {
        var error: EMError?
        PixelWorldChatEMClient.groupManager.joinPublicGroup(groupId, error: &error)
        if error?.PixelWorldChatError.code == 601 {
            // 用户已加入
            return true
        }
        return error == nil
    }
    
    //TODO: - 退出群组
    func exitGroup(_ groupId: String) -> Bool {
        var error: EMError?
        PixelWorldChatEMClient.groupManager.leaveGroup(groupId, error: &error)
        return error == nil
    }
    
    //TODO: - 获取群成员（不包含群主）
    func groupMembers(_ groupId: String) -> [Any] {
        var error: EMError?
        let group = PixelWorldChatEMClient.groupManager.getGroupSpecificationFromServer(withId: groupId, fetchMembers: true, error: &error)
        return group?.memberList ?? []
    }
    
    //TODO: - 发送群聊消息
    /// 发送群聊消息
    func sendMessage(_ body: PixelWorldChatSendMessageBody, groupId: String, resultBlock: PixelWorldChatStatusBlock? = nil) {
        guard PixelWorldChatEMClient.isLoggedIn else {
            resultBlock?(.failed(.isLoggedIn))
            return
        }
        guard body.messageBody != .none else {
            resultBlock?(.failed(.message_bodyType))
            return
        }
        if body.isSendCmdMessage && body.messageBody == .image {
            resultBlock?(.failed(.message_cmd_image))
            return
        }
        guard let fromUser = PixelWorldChatEMClient.currentUsername, fromUser != body.conversationID else {
            resultBlock?(.failed(.message_toMe))
            return
        }
        // 构建消息体
        var messageBody: EMMessageBody?
        switch body.messageBody {
        case .image:
            guard let image = body.image, let imageData = image.pngData() else {
                resultBlock?(.failed(.message_image))
                return
            }
            messageBody = EMImageMessageBody(data: imageData, thumbnailData: imageData)
            break
        case .text, .emoji, .video:
            guard !body.message.isEmpty else {
                resultBlock?(.failed(.message_text))
                return
            }
            if body.isSendCmdMessage {
                messageBody = EMCmdMessageBody(action: body.message)
            } else {
                messageBody = EMTextMessageBody(text: body.message)
            }
            break
        default:
            break
        }
        guard !body.conversationID.isEmpty else {
            resultBlock?(.failed(.message_conversationID))
            return
        }
        guard let sendBody = messageBody else { return }
        // 构建扩展消息
        let info = ["messageBody": body.messageBody.rawValue, "video_channelName": body.channelName, "sender_identifies": body.sender_identifies, "receive_identifies": body.receive_identifies, "remarks": body.remarks, "sender_chatUser": fromUser] as [String : Any]
        // 构建发送消息体
        guard let chatMessageBody = EMChatMessage(conversationID: groupId, from: fromUser, to: groupId, body: sendBody, ext: info) else {
            return
        }
        chatMessageBody.chatType = EMChatTypeGroupChat
        let model = PixelWorldChat_analysisMessages([chatMessageBody]).first
        // 发送消息
        PixelWorldChatEMClient.chatManager?.send(chatMessageBody) { _ in
            
        } completion: { message, aError in
            if let error = aError {
                resultBlock?(.failed(error.PixelWorldChatError))
            } else {
                // 直接使用 'sayWake_analysisMessages' 可能会造成控制器不能释放问题;
                if let messageBody = message, var messageModel = model {
                    if let imageBody = messageBody.body as? EMImageMessageBody {
                        messageModel.imageUrl = imageBody.remotePath
                    }
                    messageModel.mesageID = messageBody.messageId
                    resultBlock?(.messages([messageModel]))
                }
            }
        }
    }
    
}
